//
//  CookSelectView.m
//  X-Touch2
//
//  Created by shengchao yang on 12-3-28.
//  Copyright (c) 2012年 foxhis. All rights reserved.
//

#import "CookSelectView.h"
#import "Singleton.h"
#import "GridViewItemCookSort.h"
#import "GridViewItemCookDetail.h"
#import "CookCustomView.h"
#import "MessageBoxBaseView.h"
#import "NSString+Additions.h"
#import "Common.h"
#import "DataBaseAccess.h"
#import "FileManager.h"
#import "RegexKitLite.h"

@implementation CookSelectView
- (id)initWithNibName:(NSString *)nibNameOrNil withObj:(MyOrderDishes *)obj{
    _myOrderPlu = obj;
    self = [super initWithNibName:nibNameOrNil bundle:nil];
    if (self) {
        AppSession.isPopOutFullScreen = NO;
        [AppSession initSpecialCodes:0];
        lblSelectedCook = (UILabel *)[self.view viewWithTag:TagOfUILabel];
        lblPluName = (UILabel *)[self.view viewWithTag:TagOfUILabel + 1];
        if (_myOrderPlu == nil) {
            lblSelectedCook.text = @"";
            lblPluName.text = TranslateStr(@"整单备注");
        }else {
            lblSelectedCook.text = _myOrderPlu.modCook == nil ? @"":_myOrderPlu.modCook;
            lblPluName.text = [NSString stringWithFormat:@"%@[%@,%@,%@]",JsonField(_myOrderPlu.modDescripts),_myOrderPlu.pmCode,_myOrderPlu.psCode,_myOrderPlu.ppCode];
        }
        [gridViewDetail reloadData];
        
        [((UIButton *)[self.view viewWithTag:TagOfUIButton]) setTitle:TranslateStr(@"确定") forState:UIControlStateNormal];
        [((UIButton *)[self.view viewWithTag:TagOfUIButton+1]) setTitle:TranslateStr(@"全部删除") forState:UIControlStateNormal];
        [((UIButton *)[self.view viewWithTag:TagOfUIButton+2]) setTitle:TranslateStr(@"手写烧法") forState:UIControlStateNormal];
        [((UIButton *)[self.view viewWithTag:TagOfUIButton+3]) setTitle:TranslateStr(@"应用到所有菜品") forState:UIControlStateNormal];
    }
    return self;
}

- (IBAction)buttonClicked:(id)sender {
    if (AppSession.isAnimating) {
        MyNSLog(@"上一个动画还未完成...");
        return;
    }
    [AppSession playMusic:VoiceFile(@"clicked.caf")];
    NSInteger bid = [sender tag];
    if (bid == TagOfUIButton) {
        MyNSLog(@"返回我的点单界面");
        //保存烧法
        NSString * searchString = Trim(lblSelectedCook.text);
        NSString *regexString       = @"[\"%$#@!^&*()}{:?><\\/\t\r\n#'$]" ;  
        NSString *replaceWithString = @"" ;  
        NSString *pluCook = [searchString stringByReplacingOccurrencesOfRegex:regexString withString:replaceWithString];//过滤特殊字符

        if (_myOrderPlu == nil) {//整单备注
            if(pluCook.length>0){
                [DataBaseAccess Update:[NSString stringWithFormat:@"update MyOrderDishes set modCook=modCook || ',%@' where momLocalMenu='%@'",pluCook, AppSession.currentOrderMenu.momLocalMenu]];
                [AppSession initMyOrderSortedDishes];
            }
        }else {
            [_myOrderPlu updateCook:pluCook];
            postN(@"SysMsg_FullScreenMode_checkCookViewDisplay");
        }
        postN(@"SysMsg_MyOrderTableModeView_refreshMyOrderTable");//刷新我的点单界面
        NSString *SysMsg = [NSString stringWithFormat:@"SysMsg_MessageBoxBaseView_%@", self.nibName];
        postN(SysMsg);//关闭弹出窗口
    }else if(bid == TagOfUIButton + 1){
        MyNSLog(@"全部删除");
        UIAlertView *alert =[[ UIAlertView alloc] initWithTitle:TranslateStr(@"提示")
                                                        message:TranslateStr(@"删除烧法")
                                                       delegate:self 
                                              cancelButtonTitle:TranslateStr(@"取消") 
                                              otherButtonTitles:TranslateStr(@"确定"), nil];
        alert.tag = TagOfUIAlertView;
        [alert show];
        [alert release];
    }else if(bid == TagOfUIButton + 2){ 
        MyNSLog(@"弹出手写窗口");
        CookCustomView *xrmbsc = [[CookCustomView alloc] initWithNibName:@"CookCustomView" withObj:lblSelectedCook.text];
        MessageBoxBaseView *mbbv = [[MessageBoxBaseView alloc] initWithContentViewController:xrmbsc];
        CGSize size = CGSizeMake(xrmbsc.view.frame.size.width, xrmbsc.view.frame.size.height);
        CGPoint pos = CGPointMake((1024-size.width)/2, 30);
        [mbbv setContentFrame:CGRectMake(pos.x, pos.y, size.width, size.height)];        
        [self.view.superview addSubview:mbbv];
        [mbbv release];        
    }else if(bid == TagOfUIButton + 3){
        MyNSLog(@"应用到所有菜品");
        UIAlertView *alert =[[ UIAlertView alloc] initWithTitle:TranslateStr(@"提示")
                                                        message:TranslateStr(@"应用所有菜品烧法")
                                                       delegate:self 
                                              cancelButtonTitle:TranslateStr(@"取消") 
                                              otherButtonTitles:TranslateStr(@"确定"), nil];
        alert.tag = TagOfUIAlertView + 1;
        [alert show];
        [alert release];
    }
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex==alertView.cancelButtonIndex) {
        MyNSLog(@"点击了取消按钮");
    }else{
        if (alertView.tag == TagOfUIAlertView) {
            lblSelectedCook.text = @"";
            [gridViewDetail reloadData];
        }else {
            [DataBaseAccess Update:[NSString stringWithFormat:@"update MyOrderDishes set modCook='%@' where momLocalMenu='%@'",lblSelectedCook.text, AppSession.currentOrderMenu.momLocalMenu]];
            [AppSession initMyOrderSortedDishes];
        }
    }
}

#pragma mark - UIGridViewDataSource
-(NSInteger) gridViewRows:(UIGridView *)gridView{
    if (gridView.tag == TagOfUIGridView) {
        return 1;
    }else{
        return 4;
    }
}
-(NSInteger) gridViewCols:(UIGridView *)gridView{
    if (gridView.tag == TagOfUIGridView) {
        return 7;
    }else{
        return 5;
    }
}
-(NSInteger) gridViewTotalCount:(UIGridView *)gridView{
    if (gridView.tag == TagOfUIGridView) {
        return AppSession.pluSpecialSorts.count;
    }else{
        return AppSession.pluSpecialCodes.count;
    }
}
-(GridViewItem *) gridView:(UIGridView *)gridView1 itemAtIndex:(NSInteger)index{
    if (gridView1.tag == TagOfUIGridView) {
        NSString *CellIdentifier = @"CellIdentifier";
        GridViewItemCookSort *item = (GridViewItemCookSort *)[gridView1 dequeueReusableCellWithIdentifier:CellIdentifier];
        if (item == nil){
            item = [[GridViewItemCookSort alloc] init];
        }
        
//         GridViewItemCookSort *item = [[GridViewItemCookSort alloc] init];
        PluSpecialSort *temp = (PluSpecialSort *)[AppSession.pluSpecialSorts objectAtIndex:index];
        [item setData:temp];
        if (index == AppSession.specialSortIndex) {
            [item setSelectedItem:YES];
        }else {
            [item setSelectedItem:NO];
        }
        return item;
    }else{
        NSString *CellIdentifier = @"CellIdentifier1";
        GridViewItemCookDetail *item = (GridViewItemCookDetail *)[gridView1 dequeueReusableCellWithIdentifier:CellIdentifier];
        if (item == nil){
            item = [[GridViewItemCookDetail alloc] init];
        }
        
//        GridViewItemCookDetail *item = [[GridViewItemCookDetail alloc] init];
        PluSpecialCode *temp = (PluSpecialCode *)[AppSession.pluSpecialCodes objectAtIndex:index];
        [item setData:temp];
        if ([lblSelectedCook.text isContainString:JsonField(temp.pscDescripts)]) {
            [item setSelectedItem:YES];
        }else {
            [item setSelectedItem:NO];
        }
        return item;
    }
}

-(CGPoint) gridViewItemStartPoint:(UIGridView *)gridView{  //item开始位置
    return CGPointMake(0, 0);
}
-(CGSize) gridViewItemMargin:(UIGridView *)gridView{       //item之间的间隔
    if (gridView.tag == TagOfUIGridView) {
        return CGSizeMake(0, 0);
    }else{
        return CGSizeMake(6, 6);
    }
}
-(BOOL) gridViewPageControlEnable:(UIGridView *)gridView{  //是否使用pageControl控件
    return NO;
}
-(BOOL) gridViewDirection:(UIGridView *)gridView{          //滑动的方向(YES-横向默认  NO-纵向)
    if (gridView.tag == TagOfUIGridView) {
        return YES;
    }else{
        return NO;
    }
}
-(BOOL) gridViewShowScrollIndicator:(UIGridView *)gridView{//是否显示滑动条Indicator(默认NO)
    return YES;
}
#pragma mark - UIGridViewDelegate
-(void) gridView:(UIGridView *)gridView didSelectItemAtIndex:(NSInteger)index{
    AppSession.isAnimating = AppSession.isPopOutFullScreen = NO;
    if (gridView.tag == TagOfUIGridView) {
        MyNSLog(@"点击了 sort index=%d", index);
        [AppSession initSpecialCodes:index];
    }else{
        MyNSLog(@"点击了 detail index=%d", index);
        PluSpecialCode *temp = (PluSpecialCode *)[AppSession.pluSpecialCodes objectAtIndex:index];
        NSString * tempCook = [NSString stringWithFormat:@"%@", JsonField(temp.pscDescripts)];
        NSString * tempCook1 = [NSString stringWithFormat:@"%@,", JsonField(temp.pscDescripts)];
        if ([lblSelectedCook.text isContainString:tempCook]) {
            if ([lblSelectedCook.text isContainString:tempCook1]) {
                lblSelectedCook.text = [lblSelectedCook.text replaceFrom:tempCook1 To:@""];
            }else {
                lblSelectedCook.text = [lblSelectedCook.text replaceFrom:tempCook To:@""];
            }
        }else {
            if (lblSelectedCook.text == nil || lblSelectedCook.text.length==0 || [[lblSelectedCook.text substringFromIndex:lblSelectedCook.text.length-1] isEqualToString:@","]) {
                lblSelectedCook.text = tempCook;
            }else {
                lblSelectedCook.text = [NSString stringWithFormat:@"%@,%@",lblSelectedCook.text, tempCook];
            }
        }        
    }
    
    [gridViewSort reloadData];
    [gridViewDetail reloadData];
}


-(void) refreshLabelCook:(NSNotification *)note{
    NSDictionary *infos = [note userInfo];
    lblSelectedCook.text = (NSString *)[infos objectForKey:@"cookFromCustom"];
    [gridViewSort reloadData];
    [gridViewDetail reloadData];
}
#pragma mark - View lifecycle
- (void)viewDidLoad{
    addNObserver(@selector(refreshLabelCook:), @"SysMsg_CookSelectView_refreshLabelCook");
    //用自定义的九宫格view替换占位用的普通view，同时移除普通view
    UIView *tempViewSort = (UIView *)[self.view viewWithTag:TagOfUIView];
    CGRect frameSort = tempViewSort.frame;
    [tempViewSort removeFromSuperview];
    
    UIView *tempViewDetail = (UIView *)[self.view viewWithTag:TagOfUIView + 1];
    CGRect frameDetail = tempViewDetail.frame;
    [tempViewDetail removeFromSuperview];
    
    gridViewSort = [[UIGridView alloc] initWithTarget:self withFrame:frameSort withTag:TagOfUIGridView];
    gridViewSort.backgroundColor = [UIColor clearColor];
    [self.view addSubview:gridViewSort];
    
    gridViewDetail = [[UIGridView alloc] initWithTarget:self withFrame:frameDetail withTag:TagOfUIGridView + 1];
    gridViewDetail.backgroundColor = [UIColor clearColor];
    [self.view addSubview:gridViewDetail];
    
    [super viewDidLoad];
}

- (void)viewDidUnload{
    [super viewDidUnload];
}
-(void)dealloc{
    MyNSLog(@"CookSelectView is deallocing");
    removeNObserver(@"SysMsg_CookSelectView_refreshLabelCook");
    [gridViewSort release];
    [gridViewDetail release];
    [super dealloc];
}
- (void)didReceiveMemoryWarning{
    [super didReceiveMemoryWarning];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{
    return (interfaceOrientation == UIInterfaceOrientationLandscapeRight || interfaceOrientation == UIInterfaceOrientationLandscapeLeft);
}

@end
